﻿using AntDesignProCore.MVC.Models;
using Audit.Core;
using Audit.EntityFramework;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using static System.Collections.Specialized.BitVector32;
using System.Net.Http;
using System.Security.AccessControl;

namespace AntDesignProCore.MVC
{
  //原来 DbContext

  [AuditDbContext(Mode = AuditOptionMode.OptIn, IncludeEntityObjects = false, AuditEventType = "{database}_{context}")]
  public class MariaDBContext :  AuditDbContext
  {

    private readonly ILogger<MariaDBContext> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MariaDBContext(DbContextOptions<MariaDBContext> options, ILogger<MariaDBContext> logger, IHttpContextAccessor httpContextAccessor)
        : base(options)
    {
      _logger = logger;
      _httpContextAccessor = httpContextAccessor;

      // 设置审计事件
      //Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaving, scope =>
      //{
      //  // 从 HttpContext 获取当前用户
      //  var userName = _httpContextAccessor.HttpContext?.User?.Identity?.Name ?? "Anonymous";
      //  // 添加自定义字段
      //  scope.SetCustomField("UserName", userName); // Replace with actual user retrieval logic
      //});
    }

    public DbSet<AuditLog> AuditLogs { get; set; }

    public DbSet<Article> Articles { get; set; }
    public DbSet<AdIpmoveConfig> AdIpmoveConfigs { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<AreaFilter> AreaFilters { get; set; }

    //#region 重写SaveChanges 记录执行日志
    //public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    //{
    //  var changes = ChangeTracker.Entries()
    //          .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted)
    //          .ToList();
    //  // 记录日志（包含修改前后的数据）
    //  _logger.LogInformation($"重写SaveChanges 记录执行日志-------------------------------------");
    //  _logger.LogInformation($"需要处理的变更条目数: {changes.Count}");

    //  var requestPath = AuditContext.Get("RequestPath")?.ToString();
    //  var controllerName = AuditContext.Get("ControllerName")?.ToString();
    //  var actionName = AuditContext.Get("ActionName")?.ToString();
    //  var parameters = AuditContext.Get("Parameters")?.ToString();
    //  var isLogin = AuditContext.Get("IsLogin")?.ToString();
    //  _logger.LogInformation($"RequestPath: {requestPath}");
    //  _logger.LogInformation($"ControllerName: {controllerName}");
    //  _logger.LogInformation($"ActionName: {actionName}");
    //  _logger.LogInformation($"Parameters: {parameters}");
    //  _logger.LogInformation($"IsLogin: {isLogin}");

    //  List<object> addList = new List<object>();
    //  List<object> updateList = new List<object>();
    //  List<object> deleteList = new List<object>();

    //  List<object> updateOldList = new List<object>();
    //  List<object> updateNewList = new List<object>();

    //  foreach (var entry in changes)
    //  {
    //    var entityName = entry.Entity.GetType().Name;
    //    var state = entry.State.ToString();  // Added, Modified, Deleted
    //    var data = string.Empty;
    //    var oldValues = new Dictionary<string, object>();
    //    var newValues = new Dictionary<string, object>();

    //    if (entry.State == EntityState.Modified)
    //    {
    //      // 获取修改前后的数据
    //      foreach (var property in entry.OriginalValues.Properties)
    //      {
    //        var originalValue = entry.OriginalValues[property];
    //        var currentValue = entry.CurrentValues[property];

    //        if (!object.Equals(originalValue, currentValue))
    //        {
    //          oldValues[property.Name] = originalValue;
    //          newValues[property.Name] = currentValue;
    //        }
    //      }
    //    }

    //    // 获取修改前后的数据
    //    if (entry.State == EntityState.Modified)
    //    {
    //      foreach (var property in entry.OriginalValues.Properties)
    //      {
    //        var originalValue = entry.OriginalValues[property];
    //        var currentValue = entry.CurrentValues[property];

    //        if (!Equals(originalValue, currentValue))
    //        {
    //          oldValues[property.Name] = originalValue;
    //          newValues[property.Name] = currentValue;
    //        }
    //      }
    //    }
    //    //else if (entry.State == EntityState.Added)
    //    //{
    //    //  foreach (var property in entry.CurrentValues.Properties)
    //    //  {
    //    //    newValues[property.Name] = entry.CurrentValues[property];
    //    //  }
    //    //}
    //    //else if (entry.State == EntityState.Deleted)
    //    //{
    //    //  foreach (var property in entry.OriginalValues.Properties)
    //    //  {
    //    //    oldValues[property.Name] = entry.OriginalValues[property];
    //    //  }
    //    //}

    //    // 记录日志
    //    var log = new
    //    {
    //      Entity = entityName,
    //      Action = state,
    //      EntityValues= entry.Entity,
    //      OldValues = oldValues,
    //      NewValues = newValues,
    //      Timestamp = DateTime.UtcNow
    //    };

    //    switch (entry.State)
    //    {
    //      case EntityState.Added:
    //        data = $"Adding new entity: {JsonConvert.SerializeObject(entry.Entity)}";
    //        addList.Add(log);
    //        break;
    //      case EntityState.Modified:
    //        data = $"Modifying entity: {JsonConvert.SerializeObject(entry.Entity)}";
    //        updateList.Add(log);
    //        //updateOldList.Add(oldValues);
    //        //updateNewList.Add(newValues);
    //        break;
    //      case EntityState.Deleted:
    //        data = $"Deleting entity: {JsonConvert.SerializeObject(entry.Entity)}";
    //        deleteList.Add(log);
    //        break;
    //    }

    //    // 序列化为 JSON
    //    //var oldValuesJson = JsonConvert.SerializeObject(oldValues);
    //    //var newValuesJson = JsonConvert.SerializeObject(newValues);

    //    // 记录日志（包含修改前后的数据）
    //    //_logger.LogInformation($"执行类型：{action}, 实体表名：{entityName}, 数据：{data}, Old Values: {oldValuesJson}, New Values: {newValuesJson}");
    //  }

    //  _logger.LogInformation($"addList: {JsonConvert.SerializeObject(addList)}");
    //  _logger.LogInformation($"updateList: {JsonConvert.SerializeObject(updateList)}");
    //  _logger.LogInformation($"deleteList: {JsonConvert.SerializeObject(deleteList)}");

    //  //_logger.LogInformation($"updateOldList: {JsonConvert.SerializeObject(updateOldList)}");
    //  //_logger.LogInformation($"updateNewList: {JsonConvert.SerializeObject(updateNewList)}");


    //  // 调用基类的异步保存方法
    //  return await base.SaveChangesAsync(cancellationToken);
    //}
    //#endregion

  }

}
